package com.example.tangyee.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tangyee.R;
import com.example.tangyee.bean.Recipe;
import com.example.tangyee.utils.ConstantsUtil;
import com.example.tangyee.utils.GetRecipeIngredient;
import com.example.tangyee.utils.GlideApp;
import com.example.tangyee.utils.SessionidUtils;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/*

03-04 12:24:36.504 24117-24117/com.example.tangyee E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.tangyee, PID: 24117
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.ref.WeakReference.get()' on a null object reference
        at com.github.mikephil.charting.renderer.PieChartRenderer.drawExtras(PieChartRenderer.java:638)
        at com.github.mikephil.charting.charts.PieChart.onDraw(PieChart.java:131)
        at android.view.View.draw(View.java:16535)
        at android.view.View.updateDisplayListIfDirty(View.java:15525)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3702)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3682)
        at android.view.View.updateDisplayListIfDirty(View.java:15485)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3702)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3682)
        at android.view.View.updateDisplayListIfDirty(View.java:15485)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3702)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3682)
        at android.view.View.updateDisplayListIfDirty(View.java:15485)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3702)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3682)
        at android.view.View.updateDisplayListIfDirty(View.java:15485)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3702)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3682)
        at android.view.View.updateDisplayListIfDirty(View.java:15485)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3702)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3682)
        at android.view.View.updateDisplayListIfDirty(View.java:15485)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3702)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3682)
        at android.view.View.updateDisplayListIfDirty(View.java:15485)
        at android.view.View.draw(View.java:16305)
        at android.view.ViewGroup.drawChild(ViewGroup.java:3718)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3508)
        at android.view.View.draw(View.java:16538)
        at com.android.internal.policy.PhoneWindow$DecorView.draw(PhoneWindow.java:2756)
        at android.view.View.updateDisplayListIfDirty(View.java:15525)
        at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:281)
        at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:287)
        at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:322)
        at android.view.ViewRootImpl.draw(ViewRootImpl.java:2967)
        at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2779)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2397)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1268)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6638)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:926)
        at android.view.Choreographer.doCallbacks(Choreographer.java:717)
        at android.view.Choreographer.doFrame(Choreographer.java:652)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:912)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
        at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:107)

        大致查明原因，应该是绘制中心空洞的Bitmap是为 null造成的 （在PieChartRenderer中）
        可能是没设置好，现在改了一下，不知道行不行。
        * Bitmap for drawing the center hole

 */

public class RecipeDetailActivity extends AppCompatActivity {

    private static final String TAG = "RecipeDetailActivity";

    private static final String PARAM = "Recipe";

    private Unbinder mUnbinder;

    @BindView(R.id.back)
    LinearLayout back;

    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.pie_chart)
    PieChart pieChart;

    private PieData pieData;
    private String[] x = new String[] { "碳水化合物", "蛋白质", "脂肪"};
    private ArrayList<Float> y= new ArrayList<>();

    private Recipe mRecipe;

    @BindView(R.id.recipe_image)
    ImageView recipeImg;
    @BindView(R.id.calorie)
    TextView calorie;
    @BindView(R.id.textView2)
    TextView main;
    @BindView(R.id.textView4)
    TextView seasoning;
    @BindView(R.id.textView6)
    TextView method;

    @BindView(R.id.card_view)
    CardView mCardView;

    private GetRecipeIngredient mGetRecipeIngredient;
    private RepairRecipe mRepairRecipe;

    public static Intent getRecipeDetailActivityIntent(Context context, Recipe recipe) {
        Intent intent = new Intent(context, RecipeDetailActivity.class);
        intent.putExtra(PARAM, recipe);
        return intent;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe_detail);

        mUnbinder = ButterKnife.bind(this);

        mRecipe = getIntent().getParcelableExtra(PARAM);

        pieChart.setNoDataText("暂无数据");
        pieChart.setNoDataTextColor(getResources().getColor(R.color.gray));
        
        initViews();

        getRecipes();

        if (mRecipe.getImgId() != -1) {
            /*使用共享元素动画时异常，请去除ImageViwe的baground，并且不设置placeholder(...)*/
            GlideApp.with(this)
                    .load(mRecipe.getImageUrl())
                    .error(R.drawable.error)
                    .fitCenter()
                    .into(recipeImg);
        } else {
            mCardView.setVisibility(View.GONE);
            mRepairRecipe = new RepairRecipe();
            mRepairRecipe.execute();
        }
    }

    private void initViews() {
        title.setText(mRecipe.getRecipeName());
        main.setText(mRecipe.getMain());
        seasoning.setText(mRecipe.getSeasoning());
        method.setText(mRecipe.getMethod().trim());
    }

    private class RepairRecipe extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... voids) {
            if (isCancelled()) {
                return false;
            }
            try {
                SessionidUtils.updateSessionId(RecipeDetailActivity.this);
                Document document = Jsoup.connect(ConstantsUtil.GET_RECIPE_DETAIL + mRecipe.getId()).cookie("ASP.NET_SessionId", SessionidUtils.getSessionId(RecipeDetailActivity.this)).get();
                Elements divs = document.select("div.mui-pull-right");
                mRecipe.setMain(divs.get(0).text());
                mRecipe.setSeasoning(divs.get(1).text());
                mRecipe.setMethod(divs.get(2).text());
            } catch (SocketTimeoutException ste) {
                Log.e(TAG, "doInBackground: ", ste);
                return false;
            } catch (IOException e) {
                Log.e(TAG, "doInBackground: ", e);
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            if (!aBoolean) {
                Toast.makeText(RecipeDetailActivity.this, "获取信息失败", Toast.LENGTH_SHORT).show();
            }
            initViews();
        }
    }


    private void getRecipes() {
        final GetRecipeIngredient.OnPostExecute execute = ingredient -> {
            if (ingredient == null) {
                Toast.makeText(RecipeDetailActivity.this, "获取信息失败", Toast.LENGTH_SHORT).show();
                return;
            }

            if (calorie == null) {
                return;
            }
            calorie.setText("总热量：" + String.format("%.1f", ingredient.getCalorie(), Locale.CHINA) + "千卡");

            y.add(ingredient.getCarbohydrate());
            y.add(ingredient.getProtein());
            y.add(ingredient.getFat());
            showPieChart();
        };
        mGetRecipeIngredient = new GetRecipeIngredient(mRecipe.getId(), execute);
        mGetRecipeIngredient.execute();
    }

    //显示饼图
    public void showPieChart() {
        try {
            pieData = setData(y.size());
            setPieChart(pieChart, pieData);
        } catch (NullPointerException npe) {
            Log.e(TAG, "showPieChart: ", npe);
        }
    }
    //设置饼图的相关信息
    private void setPieChart(PieChart pieChart, PieData pieData) {
        if (pieChart == null || pieData == null) {
            return;
        }
        pieChart.setHighlightPerTapEnabled(false);
        //设置PieChart内部圆的半径(这里设置28.0f)
        pieChart.setHoleRadius(0f);
        //设置PieChart内部透明圆的半径(这里设置31.0f)
        pieChart.setTransparentCircleRadius(0f);
        Description description = new Description();
        description.setText("");
        description.setTextSize(15f);
        description.setPosition(400, 50);
        description.setTextColor(Color.parseColor("#ff9933"));
        pieChart.setDescription(description);
        //是否绘制PieChart内部中心文本
        pieChart.setDrawHoleEnabled(false);
        //设置pieChart图表上下左右的偏移，类似于外边距
        pieChart.setExtraOffsets(0, 0, 0, 0);
        //设置pieChart是否只显示饼图上百分比不显示文字(false只显示百分比)
        pieChart.setDrawEntryLabels(false);
        //设置pieChart图表文本字体大小
        pieChart.setEntryLabelTextSize(20f);
        //设置pieChart图表起始角度
        pieChart.setRotationAngle(-90f);
        //显示成百分比
        pieChart.setUsePercentValues(true);
        //设置可以手动旋转
        pieChart.setRotationEnabled(false);
        pieChart.setData(pieData);
        //pieChart.needsHighlight(50);
        //设置动画时间
        pieChart.animateXY(1000, 1000);
        Legend legend = pieChart.getLegend();
        //是否启用图列
        legend.setEnabled(true);
        //图例相对于图表纵向的位置
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        //图例相对于图表横向的位置
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        //图例显示的方向
        legend.setOrientation(Legend.LegendOrientation.VERTICAL);
        //设置图例的形状
        legend.setForm(Legend.LegendForm.SQUARE);
        //设置图例的大小//设置图例的大小
        legend.setFormSize(10);
        //设置每个图例实体中标签和形状之间的间距
        legend.setFormToTextSpace(10f);
        //设置图列换行(注意使用影响性能,仅适用legend位于图表下面)
        //legend.setWordWrapEnabled(false);
        //设置图例实体之间延Y轴的间距（setOrientation = VERTICAL 有效）
        legend.setYEntrySpace(5f);
        legend.setYOffset(20f);
        legend.setTextSize(10f);
        legend.setTextColor(Color.parseColor("#ff9933"));
        // pieChart.invalidate();
    }

    //添加数据到饼图中
    private PieData setData(int count) {
        // 准备x"轴"数据：在i的位置，显示x[i]字符串
        ArrayList<String> xVals = new ArrayList<>();
        // 真实的饼状图百分比分区。
        // Entry包含两个重要数据内容：position和该position的数值。
        ArrayList<PieEntry> yVals = new ArrayList<>();
        for (int xi = 0; xi < count; xi++) {
            //xVals.add(xi, x[xi]);
            // y[i]代表在x轴的i位置真实的百分比占
            yVals.add(new PieEntry(y.get(xi), x[xi]));
        }
        // 百分比占
        PieDataSet yDataSet = new PieDataSet(yVals, "");
        //设置饼状之间的间隙
        yDataSet.setSliceSpace(0);

        yDataSet.setValueLinePart1OffsetPercentage(80.f);
        yDataSet.setValueLinePart1Length(0.5f);
        yDataSet.setValueLinePart2Length(0.7f);
        yDataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        // 每个百分比占区块绘制的不同颜色
        ArrayList<Integer> colors = new ArrayList<>();
        //colors.add(Color.rgb(231, 76, 60));
        colors.add(Color.rgb(52,152,219));
        colors.add(Color.rgb(46,204,113));
        colors.add(Color.rgb(241,196,15));
        yDataSet.setColors(colors);
        // 将x轴和y轴设置给PieData作为数据源
        pieData = new PieData(yDataSet);
        //设置是否显示数据实体
        pieData.setDrawValues(true);
        //设置所有DataSet内数据实体（百分比）的文本颜色
        pieData.setValueTextColor(Color.BLUE);
        //设置所有DataSet内数据实体（百分比）的文本字体大小
        pieData.setValueTextSize(15f);
        //设置所有DataSet内数据实体（百分比）的文本字体格式
        pieData.setValueFormatter(new PercentFormatter());
        // 设置成PercentFormatter将追加%号
        pieData.setValueFormatter(new PercentFormatter());
        // 文字的颜色
        pieData.setValueTextColor(Color.BLACK);
        //pieChart.invalidate();
        return pieData;
    }

    @OnClick(R.id.back)
    public void back(View view) {
        onBackPressed();
    }

    boolean backClicked = false;
    @Override
    public void onBackPressed() {
        Log.d(TAG, "onBackPressed: " + backClicked);
        if (pieChart != null && !backClicked) {
            backClicked = true;
            pieChart.animate().alpha(0).setDuration(200).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    pieChart.setVisibility(View.GONE);
                }
            });
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mRepairRecipe != null) {
            mRepairRecipe.cancel(true);
        }
        if (mGetRecipeIngredient != null) {
            mGetRecipeIngredient.cancel(true);
        }
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }

}
